package com.handpay.zztong.hp.main.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handpay.framework.notice.ApiNoticeFactory;
import com.handpay.framework.notice.ApiNoticeListener;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.adapter.DiscoveryDataAdapter;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.base.callback.BusinessEngineListener;
import com.handpay.zztong.hp.base.fragment.BaseFragment;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.main.model.discovery.DiscoveryModel;
import com.handpay.zztong.hp.main.model.discovery.DiscoveryModleBean;
import com.handpay.zztong.hp.notification.bean.UserNoticesBean;
import com.handpay.zztong.hp.other.activity.ShowHtmlActivity;
import com.handpay.zztong.hp.utils.StatusBarUtil;

import java.util.ArrayList;

/**
 * Created by fplei on 2017/5/9.
 * 发现Modle
 */
public class DiscoveryFragment extends BaseFragment implements ApiNoticeListener, DiscoveryDataAdapter.RecyclerViewClickListener {
    private View discovery_root = null;
    private SwipeRefreshLayout swipe_refresh_widget = null;
    //child views parent
    private LinearLayout linear_parent = null;
    //synchronized object
    private Object obj = new Object();
    //this is child views
    private ArrayList<View> items = new ArrayList<View>();
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLayoutManager;
    private DiscoveryDataAdapter mAdapter;

    @Override
    public String getFragmetTitle() {
        return ZZTConstant.FRAGMENT_FLAG_DISCOVERY;
    }

    @Override
    public ActionBar getFragmentActionBar() {
        super.getFragmentActionBar();
        return new ActionBar(getFragmetTitle());
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DiscoveryModel.getInstance().setContext(getActivity());
        ApiNoticeFactory.getInstance().registerApiNoticeListener(this);
        mAdapter = new DiscoveryDataAdapter(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        HPLog.i(HPLog.TAG_RESULT, "----DiscoveryFragment---onCreateView----");
        discovery_root = inflater.inflate(R.layout.fragment_discovery, container, false);
        LinearLayout linear_title_parent = (LinearLayout) discovery_root.findViewById(R.id.linear_title_parent);
        TextView tv_titile = (TextView) discovery_root.findViewById(R.id.tv_titile);
/*        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            View fill_view = discovery_root.findViewById(R.id.fill_view);
            fill_view.setVisibility(View.GONE);
            int height = linear_title_parent.getLayoutParams().height;
            HPLog.i("result", "----height:" + height);
            LinearLayout.LayoutParams lin_params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height / 2);
            linear_title_parent.setLayoutParams(lin_params);
            tv_titile.setGravity(Gravity.CENTER);
        }*/
        // Calculate ActionBar height 根据系统ActionBarSize去计算这个布局的高度
        TypedValue tv = new TypedValue();
        if (getActivity().getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            int actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
            LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, actionBarHeight);
            lparams.gravity = Gravity.CENTER;
            linear_title_parent.setLayoutParams(lparams);
        }
        tv_titile.setText(ZZTConstant.FRAGMENT_FLAG_DISCOVERY);
        swipe_refresh_widget = (SwipeRefreshLayout) discovery_root.findViewById(R.id.swipe_refresh_widget);
        swipe_refresh_widget.setColorSchemeColors(ContextCompat.getColor(getActivity(), R.color.colorPrimary));
        //设置刷新监听
        swipe_refresh_widget.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                HPLog.i(HPLog.TAG_RESULT, "----setOnRefreshListener----");
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        swipe_refresh_widget.setRefreshing(true);
                    }
                });
                synchronized (obj) {
                    ZZTongActivity.executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            getNotices();
                        }
                    });
                }
            }
        });
        mRecyclerView = (RecyclerView) discovery_root.findViewById(R.id.recycle);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getActivity());

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL));
        mRecyclerView.setAdapter(mAdapter);
        linear_parent = (LinearLayout) discovery_root.findViewById(R.id.linear_parent_dis);
        StatusBarUtil.setTranslucentForImageViewInFragment(getActivity(), 0, linear_title_parent);
        return discovery_root;
    }

    @Override
    public void onResume() {
        super.onResume();
        bindData();
    }

    private void getNotices() {
        DiscoveryModel.getInstance().doGetNotices(new BusinessEngineListener<UserNoticesBean>() {
            @Override
            public void callbackBusinessResponse(final UserNoticesBean bean) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        swipe_refresh_widget.setRefreshing(false);
                        if (bean != null) {
                            DiscoveryModel.getInstance().updateNotices(bean);
                            bindData();
                        } else {
                            HPLog.i(HPLog.TAG_RESULT, "---DiscoveryFragment--doGetNotices---bean is null!");
                        }
                    }
                });

            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        HPLog.i(HPLog.TAG_RESULT, "----DiscovryFragment---onDestroyView---");
//        linear_parent.removeAllViews();
    }


    private void bindData() {
        LayoutInflater inflater = getActivity().getLayoutInflater();
        ArrayList<DiscoveryModleBean> disbeans = DiscoveryModel.getInstance().getItemDatas();
        mAdapter.setModleBeens(disbeans);
        HPLog.i(HPLog.TAG_RESULT, "----disbeans.size:" + disbeans.size());
        /*for (int i=0;i<disbeans.size();i++){
            if(items.size()<=0){
                items.add(i,null);
            }
            DiscoveryModleBean bean=disbeans.get(i);
            View discoveryItem_rootView=null;
            if(items.get(i)==null) {
                discoveryItem_rootView = inflater.inflate(R.layout.fragment_discovery_item, null);
                discoveryItem_rootView.setTag(bean.getTag()+i);
                discoveryItem_rootView.setId(i*10);
                items.add(i,discoveryItem_rootView);
            }else{
                discoveryItem_rootView=items.get(i);
            }
            LinearLayout linear=(LinearLayout)discoveryItem_rootView.findViewById(R.id.linear_parent);
            linear.setTag(bean.getTag());
            linear.setOnClickListener(this);
            ImageView img_icon=(ImageView)discoveryItem_rootView.findViewById(R.id.img_icon);
            img_icon.setBackgroundResource(bean.getItem_icon());
            TextView tv_title=(TextView)discoveryItem_rootView.findViewById(R.id.tv_title);
            tv_title.setText(bean.getItem_title());
            ImageView img_newflag=(ImageView)discoveryItem_rootView.findViewById(R.id.img_newflag);
            if(bean.getIsNewFlag()>0){
                img_newflag.setVisibility(View.VISIBLE);
            }else {
                img_newflag.setVisibility(View.INVISIBLE);
            }
            View line_top=getLineView(disbeans.size(),i);
            HPLog.i(HPLog.TAG_RESULT,"linear_parent.getChildCount():"+linear_parent.getChildCount());
            //由于本身linear_parent下存在一个View
            if((linear_parent.getChildCount()-(disbeans.size()+1))<=disbeans.size()){
                linear_parent.addView(line_top);
                linear_parent.addView(discoveryItem_rootView);
                if(i+1==disbeans.size()){
                    linear_parent.addView(getLineView(disbeans.size(),i+1));
                }
            }
            HPLog.i(HPLog.TAG_RESULT,"linear_parent.getChildCount():"+linear_parent.getChildCount());
        }*/
    }

    /**
     * 分割线中间的都是需要 左右缩进
     *
     * @param totleCount
     * @param index
     * @return
     */
    private View getLineView(int totleCount, int index) {
        LinearLayout.LayoutParams linesParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1);
        //由于父view 为 LinearLayout且垂直布局，直接添加line设置Margin 会有空隙显示父类view的背景颜色
        LinearLayout ll_line_parent = new LinearLayout(getActivity());
        ll_line_parent.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.background_white_color));
        View line = new View(getActivity());
        line.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.light_grey_color));
        //如果不是第一条也不是最后一条
        if (index > 0 && index < totleCount && index != totleCount) {
            HPLog.i(HPLog.TAG_RESULT, "----index:" + index);
            linesParams.leftMargin = 30;
            linesParams.rightMargin = 30;
        }
        line.setLayoutParams(linesParams);
        ll_line_parent.addView(line);
        return ll_line_parent;
    }


    @Override
    public void onNotifyNotice(int action, Bundle bundle) {
        HPLog.i(HPLog.TAG_RESULT, "----DiscoveryFragment---onNotifyNotice----");
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                bindData();
            }
        });
    }

    @Override
    public int[] getNoticeAction() {
        int actions[] = {NOTICE_ACTION};
        return actions;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        for (int i = 0; i < items.size(); i++) {
            items.clear();
        }
        DiscoveryModel.getInstance().onDestroy();
        if (mAdapter != null) {
            mAdapter.destory();
        }
        ApiNoticeFactory.getInstance().unregisterApiNoticeListener(this);
    }


    @Override
    public void OnItemClick(DiscoveryModleBean bean) {
        if (bean == null) return;
        Intent intent = new Intent();
        intent.setClass(getActivity(), bean.getClazz());
        if (bean.getTag().equals("1")) {
            intent.putExtra(ShowHtmlActivity.ShowHtml_Title_Key, "最新资讯");
            intent.putExtra(ShowHtmlActivity.ShowHtml_Html_Path_Key, bean.getPrepareField());
        }
        startActivity(intent);
    }
}
